隨著人工智慧的迅速發展,將 AI 整合入應用程式的需求越來越高。在這篇文章中,我們將學習如何在 Android Studio 上使用 OpenAI 的 API,將 GPT 整合進你的專案中,並讓它為使用者提供智能對話和建議
OpenAI API 金鑰:前往 OpenAI 的官網 註冊並獲取 API 金鑰。
在你的專案中的 build.gradle (Module: app) 文件中添加 OkHttp 和 JSON 處理的依賴。
dependencies {
    implementation 'com.squareup.okhttp3:okhttp:4.9.3'
    implementation 'org.json:json:20210307' // 用於處理 JSON
}
在 AndroidManifest.xml 中添加網絡訪問的權限,確保你的應用可以訪問互聯網。
<uses-permission android:name="android.permission.INTERNET"/>
接下來,創建 API 請求的函數:
public class MainActivity extends AppCompatActivity {
    
    private static final String API_KEY = "你的_API_金鑰"; // 將這裡替換成你的 API 金鑰
    private static final String OPENAI_API_URL = "https://api.openai.com/v1/chat/completions";
    private EditText userInput;
    private TextView resultTextView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        userInput = findViewById(R.id.userInput);
        resultTextView = findViewById(R.id.resultTextView);
        Button submitButton = findViewById(R.id.submitButton);
        submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String inputText = userInput.getText().toString();
                if (!inputText.isEmpty()) {
                    callOpenAI(inputText);
                }
            }
        });
    }
    private void callOpenAI(String input) {
        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/json");
        JSONObject jsonBody = new JSONObject();
        try {
            jsonBody.put("model", "gpt-3.5-turbo");
            JSONArray messages = new JSONArray();
            JSONObject message = new JSONObject();
            message.put("role", "user");
            message.put("content", input);
            messages.put(message);
            jsonBody.put("messages", messages);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody body = RequestBody.create(mediaType, jsonBody.toString());
        Request request = new Request.Builder()
                .url(OPENAI_API_URL)
                .post(body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "Bearer " + API_KEY)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful() && response.body() != null) {
                    String responseData = response.body().string();
                    parseOpenAIResponse(responseData);
                }
            }
        });
    }
    private void parseOpenAIResponse(String responseData) {
        try {
            JSONObject jsonResponse = new JSONObject(responseData);
            String aiResponse = jsonResponse.getJSONArray("choices").getJSONObject(0)
                    .getJSONObject("message").getString("content");
            runOnUiThread(() -> resultTextView.setText(aiResponse));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
在 res/layout/activity_main.xml 中設計簡單的 UI,讓用戶能夠輸入問題並顯示 GPT 的返回結果。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp">
    <EditText
        android:id="@+id/userInput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="請輸入你的問題" />
    <Button
        android:id="@+id/submitButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="提交" />
    <TextView
        android:id="@+id/resultTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="GPT的回答將顯示在這裡"
        android:paddingTop="16dp" />
</LinearLayout>
讓 GPT 可以在你的應用程式中與用戶進行互動。隨著時間的推進,你可以根據需求進一步來擴展功能,像是添加上下文記憶、自動回應、或與其他 API 的結合等。
這只是一個基本的開始,探索人工智慧的更多潛力和應用是非常值得的!祝你在開發中取得成功!